package com.kehutong.message.service;

import com.kehutong.message.enums.WebChatApiSuffix;
import com.kehutong.message.urlConfig.WebChatUrlConfig;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.util.Objects;

/**
 * 微信发送消息
 * 
 * @author liuzhen (liuxing521a@163.com)
 * @createTime 2020年5月20日 上午10:52:03
 */
@WebService("/message/webchat")
public class WebchatMessageService {
	
	@Inject
	private WebChatUrlConfig webChatConfig;

	/**
	 * <p>发送微信公众号消息</p>
	 * @param json
	 * @throws Exception
	 */
	@ReqMapping("/sendShare")
	public void sendShare(JSONObject json) throws Exception {
		String access_token = json.getString("access_token");

		send(access_token, getSendWebChatShareJson(json), WebChatApiSuffix.MSG_TEMPLATE_SEND);

	}

	private JSONObject getSendWebChatShareJson(JSONObject json){
		JSONObject body = new JSONObject();
		body.put("touser", json.getString("openid"));
		body.put("template_id", json.getString("templateNo"));
		body.put("url", json.getString("url"));
		body.put("data", json.getJSONObject("data"));

		return body;
	}

	/**
	 * 发送http请求
	 * @param access_token 对应公众号/小程序的token
	 * @param json body
	 * @param pageSuffix 接口地址后缀
	 * @throws Exception
	 */
	private void send(String access_token, JSONObject json, WebChatApiSuffix pageSuffix) throws Exception {
		if (Objects.isEmpty(access_token)) {
			return;
		}
		if (Objects.isNull(json)) {
			return;
		}

		webChatConfig.post(pageSuffix.getSuffix(), http -> {
			http.addParam("access_token", access_token);
			http.setBody(json.toJSONString());
		});
	}
}
